#!/bin/bash

# Ubuntu + Nginx 一键部署脚本
# 使用方法: ./deploy-ubuntu.sh [命令] [选项]

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_message() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_header() {
    echo -e "${BLUE}================================${NC}"
    echo -e "${BLUE}  Ubuntu + Nginx 部署脚本${NC}"
    echo -e "${BLUE}================================${NC}"
}

# 检查系统环境
check_system() {
    print_message "检查系统环境..."
    
    # 检查是否为Ubuntu
    if ! grep -q "Ubuntu" /etc/os-release; then
        print_warning "检测到非Ubuntu系统，脚本可能不完全兼容"
    fi
    
    # 检查Docker
    if ! command -v docker &> /dev/null; then
        print_error "Docker 未安装"
        print_message "正在安装 Docker..."
        install_docker
    fi
    
    # 检查Docker Compose
    if ! command -v docker-compose &> /dev/null; then
        print_error "Docker Compose 未安装"
        print_message "正在安装 Docker Compose..."
        install_docker_compose
    fi
    
    # 检查Nginx (系统级，可选)
    if ! command -v nginx &> /dev/null; then
        print_warning "系统未安装Nginx，将使用Docker中的Nginx"
    fi
    
    print_message "系统环境检查完成"
}

# 安装Docker
install_docker() {
    print_message "安装 Docker..."
    
    # 更新包索引
    sudo apt-get update
    
    # 安装必要的包
    sudo apt-get install -y \
        apt-transport-https \
        ca-certificates \
        curl \
        gnupg \
        lsb-release
    
    # 添加Docker官方GPG密钥
    curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
    
    # 设置稳定版仓库
    echo \
        "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu \
        $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
    
    # 更新包索引
    sudo apt-get update
    
    # 安装Docker Engine
    sudo apt-get install -y docker-ce docker-ce-cli containerd.io
    
    # 启动Docker服务
    sudo systemctl start docker
    sudo systemctl enable docker
    
    # 将当前用户添加到docker组
    sudo usermod -aG docker $USER
    
    print_message "Docker 安装完成"
    print_warning "请重新登录或运行 'newgrp docker' 以使组权限生效"
}

# 安装Docker Compose
install_docker_compose() {
    print_message "安装 Docker Compose..."
    
    # 获取最新版本号
    COMPOSE_VERSION=$(curl -s https://api.github.com/repos/docker/compose/releases/latest | grep 'tag_name' | cut -d\" -f4)
    
    # 下载Docker Compose
    sudo curl -L "https://github.com/docker/compose/releases/download/${COMPOSE_VERSION}/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
    
    # 添加执行权限
    sudo chmod +x /usr/local/bin/docker-compose
    
    # 创建软链接
    sudo ln -sf /usr/local/bin/docker-compose /usr/bin/docker-compose
    
    print_message "Docker Compose 安装完成"
}

# 检查环境变量文件
check_env_file() {
    if [ ! -f ".env.production" ]; then
        print_warning "未找到 .env.production 文件"
        if [ -f "env.production.template" ]; then
            print_message "正在创建 .env.production 文件..."
            cp env.production.template .env.production
            print_warning "请编辑 .env.production 文件，填入正确的配置信息"
            print_warning "特别是 AI API 密钥等敏感信息"
            read -p "按 Enter 键继续，或 Ctrl+C 退出编辑配置..."
        else
            print_error "未找到环境变量模板文件"
            exit 1
        fi
    fi
    print_message "环境变量文件检查通过"
}

# 创建必要的目录
create_directories() {
    print_message "创建必要的目录..."
    
    # 创建nginx配置目录
    mkdir -p nginx/ssl
    mkdir -p logs/nginx
    mkdir -p logs/app
    
    # 设置权限
    chmod 755 nginx
    chmod 755 logs
    
    print_message "目录创建完成"
}

# 构建镜像
build_image() {
    print_message "开始构建 Docker 镜像..."
    docker-compose build --no-cache
    print_message "Docker 镜像构建完成"
}

# 启动服务
start_services() {
    print_message "启动服务..."
    docker-compose up -d
    print_message "服务启动完成"
    
    # 等待服务启动
    print_message "等待服务启动..."
    sleep 15
    
    # 检查服务状态
    if docker-compose ps | grep -q "Up"; then
        print_message "服务运行正常"
        print_message "应用访问地址: http://localhost"
        print_message "Nginx状态: http://localhost/health"
    else
        print_error "服务启动失败，请检查日志"
        docker-compose logs
        exit 1
    fi
}

# 停止服务
stop_services() {
    print_message "停止服务..."
    docker-compose down
    print_message "服务已停止"
}

# 重启服务
restart_services() {
    print_message "重启服务..."
    docker-compose restart
    print_message "服务重启完成"
}

# 查看日志
show_logs() {
    local service=${1:-""}
    if [ -n "$service" ]; then
        print_message "显示 $service 服务日志..."
        docker-compose logs -f "$service"
    else
        print_message "显示所有服务日志..."
        docker-compose logs -f
    fi
}

# 查看服务状态
show_status() {
    print_message "服务状态:"
    docker-compose ps
    echo ""
    print_message "Docker 资源使用情况:"
    docker stats --no-stream
    echo ""
    print_message "Nginx 访问日志 (最近10条):"
    docker-compose logs --tail=10 nginx
}

# 清理资源
cleanup() {
    print_message "清理未使用的 Docker 资源..."
    docker system prune -f
    print_message "清理完成"
}

# 备份数据
backup_data() {
    local backup_dir="backup/$(date +%Y%m%d_%H%M%S)"
    print_message "创建备份目录: $backup_dir"
    mkdir -p "$backup_dir"
    
    # 备份环境变量
    if [ -f ".env.production" ]; then
        cp .env.production "$backup_dir/"
        print_message "已备份环境变量文件"
    fi
    
    # 备份nginx配置
    if [ -d "nginx" ]; then
        cp -r nginx "$backup_dir/"
        print_message "已备份Nginx配置"
    fi
    
    # 备份日志
    if [ -d "logs" ]; then
        cp -r logs "$backup_dir/"
        print_message "已备份日志文件"
    fi
    
    print_message "备份完成: $backup_dir"
}

# 显示帮助信息
show_help() {
    echo "使用方法: $0 [命令] [选项]"
    echo ""
    echo "命令:"
    echo "  install     安装Docker和Docker Compose"
    echo "  build       构建 Docker 镜像"
    echo "  up          启动服务"
    echo "  down        停止服务"
    echo "  restart     重启服务"
    echo "  logs [服务] 查看日志 (可选指定服务名)"
    echo "  status      查看服务状态"
    echo "  cleanup     清理 Docker 资源"
    echo "  backup      备份数据"
    echo "  help        显示帮助信息"
    echo ""
    echo "选项:"
    echo "  --no-cache    构建时不使用缓存"
    echo "  --follow      查看日志时跟随输出"
    echo ""
    echo "示例:"
    echo "  $0 install         # 安装Docker环境"
    echo "  $0 build           # 构建镜像"
    echo "  $0 up              # 启动服务"
    echo "  $0 logs nginx      # 查看Nginx日志"
    echo "  $0 logs app        # 查看应用日志"
    echo "  $0 status          # 查看服务状态"
    echo "  $0 down            # 停止服务"
}

# 主函数
main() {
    print_header
    
    # 检查系统环境
    check_system
    
    # 创建必要目录
    create_directories
    
    # 检查环境变量文件
    check_env_file
    
    # 解析参数
    COMMAND=${1:-"up"}
    
    case $COMMAND in
        "install")
            print_message "Docker环境已准备就绪"
            ;;
        "build")
            build_image
            ;;
        "up")
            build_image
            start_services
            ;;
        "down")
            stop_services
            ;;
        "restart")
            restart_services
            ;;
        "logs")
            show_logs "$2"
            ;;
        "status")
            show_status
            ;;
        "cleanup")
            cleanup
            ;;
        "backup")
            backup_data
            ;;
        "help"|"-h"|"--help")
            show_help
            ;;
        *)
            print_error "未知命令: $COMMAND"
            show_help
            exit 1
            ;;
    esac
}

# 执行主函数
main "$@"
